<template>
  <div class="device-manager">
    <!-- 标题控制栏 -->
    <div class="control-bar">
      <div class="group-selector">
        <select v-model="currentGroup" @change="handleGroupChange" class="group-dropdown">
          <option v-for="(group, index) in groupList" :key="index" :value="group.id">
            {{ group.name }}
          </option>
        </select>
        <button class="new-group-btn" @click="showCreateDialog">
          <i class="icon-plus"></i> 新建分组
        </button>
        <!-- 新增删除分组按钮 -->
        <button
          class="delete-group-btn"
          @click="showDeleteDialog"
          :disabled="groupList.length <= 1"
        >
          <i class="icon-trash"></i> 删除分组
        </button>
      </div>

      <div class="mode-switch">
        <div
          class="mode-radio"
          v-for="mode in modes"
          :key="mode.value"
          :class="{ 'mode-radio-active': currentMode === mode.value }"
          @click="currentMode = mode.value"
        >
          {{ mode.label }}
        </div>
      </div>
    </div>

    <!-- 设备信息展示 -->
    <div class="device-panels">
      <div v-for="(device, index) in currentDevices" :key="index" class="device-card">
        <h3 class="device-title">设备 {{ index + 1 }}</h3>
        <div class="device-status">
          <div class="status-item">
            <span class="label">状态：</span>
            <span class="value">
              <span class="current-value" :class="device.status">
                {{ statusMap[device.status] }}
              </span>
              <span class="preset-value">(预设: {{ statusMap[device.preset.status] }})</span>
            </span>
          </div>
          <div class="status-item">
            <span class="label">电量：</span>
            <span class="value">
              <span class="current-value">{{ device.battery }}%</span>
              <span class="preset-value">(预设: {{ device.preset.battery }}%)</span>
            </span>
          </div>
          <div v-if="device.temperature" class="status-item">
            <span class="label">温度：</span>
            <span class="value">
              <span class="current-value">{{ device.temperature }}℃</span>
              <span class="preset-value">(预设: {{ device.preset.temperature }}℃)</span>
            </span>
          </div>
        </div>
        <div class="device-id">编号：{{ device.id }}</div>
        <button class="modify-btn" @click="showModifyDialog(device)">修改预设参数</button>
      </div>
    </div>

    <!-- 传感器面板 -->
    <div class="sensor-panels">
      <div v-for="(sensor, type) in sensorData" :key="type" class="sensor-card">
        <div class="sensor-header">
          <div class="sensor-title">{{ sensorTypeMap[type] }}</div>
          <select
            v-model="selectedSensors[type]"
            @change="handleSensorChange(type)"
            class="sensor-dropdown"
          >
            <option v-for="device in sensorDevices[type]" :key="device.id" :value="device.id">
              {{ device.id }}
            </option>
          </select>
        </div>
        <div class="sensor-value">
          {{ sensor.currentValue }}
        </div>
        <div class="sensor-info">最新更新：{{ sensor.updateTime }}</div>
      </div>
    </div>

    <!-- 新建分组对话框 -->
    <div v-if="showCreateGroup" class="create-group-modal">
      <div class="modal-content">
        <h3 class="modal-title">新建分组</h3>
        <div class="modal-form">
          <div class="form-group">
            <label for="group-name">分组名称</label>
            <input
              type="text"
              id="group-name"
              v-model="newGroupForm.name"
              :class="{ 'form-error': groupErrors.name }"
              placeholder="请输入分组名称"
            />
            <div v-if="groupErrors.name" class="error-message">{{ groupErrors.name }}</div>
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn-cancel" @click="showCreateGroup = false">取消</button>
          <button class="btn-confirm" @click="confirmCreateGroup">确认</button>
        </div>
      </div>
    </div>

    <!-- HTML模板中添加删除分组对话框 -->
    <div v-if="showDeleteGroup" class="delete-group-modal">
      <div class="modal-content">
        <h3 class="modal-title">删除分组</h3>
        <div class="modal-form">
          <div class="form-group">
            <p>
              确定要删除 <span class="delete-group-name">{{ currentGroupInfo.name }}</span> 分组吗？
            </p>
            <p class="form-note">该分组下的所有设备将移至默认分组。</p>
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn-cancel" @click="showDeleteGroup = false">取消</button>
          <button class="btn-confirm" @click="confirmDeleteGroup">确认删除</button>
        </div>
      </div>
    </div>

    <!-- 修改参数对话框 -->
    <div v-if="showModifyParams" class="modify-params-modal">
      <div class="modal-content">
        <h3 class="modal-title">修改预设参数 - {{ currentDevice.id }}</h3>
        <div class="modal-form">
          <div class="form-group">
            <label>设备状态</label>
            <div class="status-radio-group">
              <label class="status-radio">
                <input type="radio" v-model="deviceParams.status" value="normal" />
                <span class="status-radio-text normal">正常</span>
              </label>
              <label class="status-radio">
                <input type="radio" v-model="deviceParams.status" value="standby" />
                <span class="status-radio-text standby">待机</span>
              </label>
              <label class="status-radio">
                <input type="radio" v-model="deviceParams.status" value="offline" />
                <span class="status-radio-text offline">离线</span>
              </label>
            </div>
          </div>

          <div class="form-group">
            <label>预设电量 (%)</label>
            <input
              type="number"
              v-model.number="deviceParams.battery"
              min="0"
              max="100"
              :class="{ 'form-error': batteryError }"
            />
            <div v-if="batteryError" class="error-message">{{ batteryError }}</div>
          </div>

          <div class="form-group" v-if="deviceParams.showTemperature">
            <label>预设温度 (℃)</label>
            <input
              type="number"
              v-model.number="deviceParams.temperature"
              :class="{ 'form-error': temperatureError }"
            />
            <div v-if="temperatureError" class="error-message">{{ temperatureError }}</div>
          </div>

          <div class="form-note">
            <p>提示：修改预设参数不会立即影响当前设备状态，需通过系统同步后生效。</p>
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn-cancel" @click="showModifyParams = false">取消</button>
          <button class="btn-confirm" @click="confirmModifyParams">保存预设</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分组相关
      groupList: [
        { id: 'default', name: '默认分组' },
        { id: 'group1', name: '办公区设备' }
      ],
      currentGroup: 'default',
      showCreateGroup: false,
      newGroupForm: { name: '' },
      groupErrors: { name: '' },

      // 模式相关
      currentMode: 'manual',
      modes: [
        { value: 'manual', label: '手动模式' },
        { value: 'auto', label: '自动模式' },
        { value: 'smart', label: '智能模式' }
      ],

      // 设备数据
      currentDevices: [
        {
          id: 'T-001',
          status: 'normal',
          battery: 75,
          temperature: 22,
          showTemperature: true,
          preset: {
            status: 'normal',
            battery: 80,
            temperature: 25
          }
        },
        {
          id: 'H-002',
          status: 'standby',
          battery: 60,
          showTemperature: false,
          preset: {
            status: 'normal',
            battery: 90
          }
        }
      ],
      currentDevice: null,
      showModifyParams: false,
      deviceParams: {
        status: 'normal',
        battery: 100,
        temperature: 25,
        showTemperature: true
      },
      batteryError: '',
      temperatureError: '',

      showDeleteGroup: false, // 删除分组对话框显示状态
      currentGroupInfo: null, // 当前选中的分组信息

      // 传感器相关
      sensorDevices: {
        temperature: [
          { id: 'T-001', currentValue: '22℃', updateTime: '10:30:21' },
          { id: 'T-003', currentValue: '24℃', updateTime: '10:29:55' }
        ],
        humidity: [
          { id: 'H-002', currentValue: '50%', updateTime: '10:30:15' },
          { id: 'H-004', currentValue: '48%', updateTime: '10:29:45' }
        ],
        pm25: [
          { id: 'PM-003', currentValue: '15μg/m³', updateTime: '10:30:05' },
          { id: 'PM-005', currentValue: '18μg/m³', updateTime: '10:29:35' }
        ]
      },
      selectedSensors: {
        temperature: 'T-001',
        humidity: 'H-002',
        pm25: 'PM-003'
      }
    }
  },

  computed: {
    statusMap() {
      return {
        normal: '正常',
        standby: '待机',
        offline: '离线'
      }
    },
    sensorTypeMap() {
      return {
        temperature: '温度传感器',
        humidity: '湿度传感器',
        pm25: 'PM2.5传感器'
      }
    },
    sensorData() {
      return Object.keys(this.selectedSensors).reduce((acc, type) => {
        const device = this.sensorDevices[type].find((d) => d.id === this.selectedSensors[type])
        acc[type] = device
        return acc
      }, {})
    }
  },

  methods: {
    handleGroupChange(val) {
      console.log('分组变更:', val)
    },
    showCreateDialog() {
      this.showCreateGroup = true
      this.newGroupForm.name = ''
      this.groupErrors.name = ''
    },
    confirmCreateGroup() {
      this.validateGroupForm()

      if (!this.groupErrors.name) {
        this.groupList.push({
          id: `group${this.groupList.length + 1}`,
          name: this.newGroupForm.name
        })
        this.showCreateGroup = false
        this.currentGroup = `group${this.groupList.length}`
      }
    },
    validateGroupForm() {
      this.groupErrors.name = ''

      if (!this.newGroupForm.name) {
        this.groupErrors.name = '请输入分组名称'
      } else if (this.newGroupForm.name.length < 2 || this.newGroupForm.name.length > 8) {
        this.groupErrors.name = '长度应在2到8个字符之间'
      }
    },

    showModifyDialog(device) {
      this.currentDevice = device
      this.deviceParams = {
        status: device.preset.status,
        battery: device.preset.battery,
        temperature: device.preset.temperature || 25,
        showTemperature: device.hasOwnProperty('temperature')
      }
      this.batteryError = ''
      this.temperatureError = ''
      this.showModifyParams = true
    },

    confirmModifyParams() {
      this.validateDeviceParams()

      if (!this.batteryError && (!this.deviceParams.showTemperature || !this.temperatureError)) {
        // 更新预设参数
        this.currentDevice.preset.status = this.deviceParams.status
        this.currentDevice.preset.battery = this.deviceParams.battery

        if (this.deviceParams.showTemperature) {
          this.currentDevice.preset.temperature = this.deviceParams.temperature
        }

        this.showModifyParams = false
        this.$message({
          type: 'success',
          message: '预设参数已保存，等待系统同步'
        })
      }
    },

    validateDeviceParams() {
      this.batteryError = ''
      this.temperatureError = ''

      // 验证电量
      if (
        isNaN(this.deviceParams.battery) ||
        this.deviceParams.battery < 0 ||
        this.deviceParams.battery > 100
      ) {
        this.batteryError = '请输入0-100之间的数字'
      }

      // 验证温度
      if (
        this.deviceParams.showTemperature &&
        (isNaN(this.deviceParams.temperature) ||
          this.deviceParams.temperature < -20 ||
          this.deviceParams.temperature > 80)
      ) {
        this.temperatureError = '请输入-20-80之间的数字'
      }
    },

    // 显示删除分组对话框
    showDeleteDialog() {
      // 获取当前选中的分组信息
      this.currentGroupInfo = this.groupList.find((group) => group.id === this.currentGroup)
      this.showDeleteGroup = true
    },

    // 确认删除分组
    confirmDeleteGroup() {
      if (!this.currentGroupInfo) return

      // 过滤掉当前分组（默认分组不允许删除）
      if (this.currentGroup === 'default') {
        this.$message.error('默认分组不允许删除')
        this.showDeleteGroup = false
        return
      }

      // 删除分组
      this.groupList = this.groupList.filter((group) => group.id !== this.currentGroup)

      // 切换到默认分组
      this.currentGroup = 'default'
      this.showDeleteGroup = false

      this.$message.success('分组删除成功')
    },

    modifyPara(DeviceId) {
      const device = this.currentDevices.find((d) => d.id === DeviceId)
      if (device) {
        this.showModifyDialog(device)
      }
    },

    handleSensorChange(type) {
      console.log(`切换${type}传感器设备：`, this.selectedSensors[type])
    }
  }
}
</script>

<style scoped>
/* 基础样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Arial', sans-serif;
}

.device-manager {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

/* 控制栏样式 */
.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.group-selector {
  display: flex;
  align-items: center;
}

.group-dropdown {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 10px;
  font-size: 14px;
}

.new-group-btn {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.new-group-btn:hover {
  background-color: #38a169;
}

.icon-plus::before {
  content: '+';
  margin-right: 5px;
}

.mode-switch {
  display: flex;
  gap: 15px;
}

.mode-radio {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.mode-radio-active {
  background-color: #42b983;
  color: white;
  border-color: #42b983;
}

/* 设备卡片样式 */
.device-panels {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.device-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.device-title {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.label {
  color: #909399;
}

.value {
  color: #606266;
}

.current-value {
  font-weight: bold;
}

.current-value.normal {
  color: #67c23a;
}

.current-value.standby {
  color: #e6a23c;
}

.current-value.offline {
  color: #f56c6c;
}

.preset-value {
  font-size: 12px;
  color: #909399;
  margin-left: 5px;
}

.device-id {
  margin-top: 12px;
  font-size: 12px;
  color: #909399;
}

.modify-btn {
  margin-top: 15px;
  padding: 6px 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.modify-btn:hover {
  background-color: #368ee0;
}

/* 传感器面板样式 */
.sensor-panels {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.sensor-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 15px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  text-align: center;
}

.sensor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.sensor-title {
  font-size: 14px;
  color: #606266;
}

.sensor-dropdown {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}

.sensor-value {
  font-size: 24px;
  color: #303133;
  margin: 20px 0;
}

.sensor-info {
  font-size: 12px;
  color: #909399;
  text-align: right;
}

/* 新建分组模态框样式 */
.create-group-modal,
.modify-params-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 0; /* 确保内容与新建分组对话框边距一致 */
}

.modal-title {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  font-size: 16px;
  color: #303133;
}

.modal-form {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #606266;
}

.form-group input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:focus {
  outline: none;
  border-color: #42b983;
}

.form-error {
  border-color: #f56c6c !important;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.form-note {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #909399;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.btn-cancel,
.btn-confirm {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  border: none;
  margin-left: 10px;
}

.btn-cancel {
  background-color: #fff;
  color: #606266;
  border: 1px solid #ddd;
}

.btn-confirm {
  background-color: #42b983;
  color: white;
}

.btn-cancel:hover,
.btn-confirm:hover {
  opacity: 0.9;
}

/* 状态选择器样式 */
.status-radio-group {
  display: flex;
  gap: 15px;
}

.status-radio {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.status-radio input {
  margin-right: 5px;
}

.status-radio-text {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.status-radio-text.normal {
  color: #67c23a;
  border: 1px solid #67c23a;
}

.status-radio-text.standby {
  color: #e6a23c;
  border: 1px solid #e6a23c;
}

.status-radio-text.offline {
  color: #f56c6c;
  border: 1px solid #f56c6c;
}

.status-radio input:checked + .status-radio-text.normal {
  background-color: #67c23a;
  color: white;
}

.status-radio input:checked + .status-radio-text.standby {
  background-color: #e6a23c;
  color: white;
}

.status-radio input:checked + .status-radio-text.offline {
  background-color: #f56c6c;
  color: white;
}

/* 新增删除分组按钮样式 */
.delete-group-btn {
  padding: 8px 16px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  margin-left: 10px; /* 与新建分组按钮间隔 */
}

.delete-group-btn:hover {
  background-color: #c0392b;
}

.delete-group-btn:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.icon-trash::before {
  content: '-';
  margin-right: 5px;
}

/* 删除分组对话框样式（可复用原有模态框样式，新增提示文本样式） */
.delete-group-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.form-confirm,
.delete-group-name {
  color: #e74c3c;
  font-weight: bold;
}

.delete-note {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}
</style>